package com.central.apps.controller;

import com.central.apps.util.TemplateUtils;
import com.central.common.web.Result;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author mengweitao
 * @Date 2023/3/13/013 14:37
 */
@RestController
@RequestMapping("/template")
public class TemplateController {

    @Resource
    private ResourceLoader resourceLoader;

    @PostMapping("/downloadTemplate")
    public Result downloadTemplate(HttpServletRequest req , HttpServletResponse resp, @RequestBody Map<String,Object> params ) throws IOException {
        String fileKey = MapUtils.getString(params, "fileKey");
        String filePath = TemplateUtils.downloadOrgTemplate(fileKey);
        if(StringUtils.isBlank(filePath)){
            return Result.failed("未找到指定模板！");
        }
        String fileName = filePath.substring(16);
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;

        if(StringUtils.isNotBlank(filePath)){
            try {
                org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:"+filePath);
                inputStream = resource.getInputStream();
                servletOutputStream = resp.getOutputStream();
                IOUtils.copy(inputStream, servletOutputStream);
                resp.flushBuffer();
                String exportFileName =fileName;
                String fileNameURL = URLEncoder.encode(exportFileName, "UTF-8");
                resp.setHeader("Content-disposition", "attachment;filename="+fileNameURL+";"+"filename*=utf-8''"+fileNameURL);
                resp.setContentType("application/octet-stream");
                inputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return Result.succeed("操作成功");
    }
}
